package com.jinlejia.erp.ui.customer;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.freedom.yefeng.yfrecyclerview.YfListMode;
import com.freedom.yefeng.yfrecyclerview.YfLoadMoreListener;
import com.jinlejia.erp.R;
import com.jinlejia.erp.adapter.LookatAdapter;
import com.jinlejia.erp.adapter.NewLookatAdapter;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.common.WrapContentLinearLayoutManager;
import com.jinlejia.erp.databinding.FragmentLookAtBinding;
import com.jinlejia.erp.ui.mine.adapter.GirdDropDownAdapter;
import com.jinlejia.erp.ui.mine.adapter.TimeDropDownAdapter;
import com.jinlejia.erp.utils.DataFilter;
import com.jinlejia.erp.utils.DateUtil;
import com.jinlejia.erp.utils.StringUtil;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;

/**
 * 带看（Fragment）
 */

public class LookAtFragment extends Fragment implements OnDateSetListener, YfLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {

    private View view;

    private String headers[] = {"二手房", "带看时间"};
    private String typeArr[] = {"二手房", "新房"};
    private String time[] = {"最早日期", "最晚日期"};

    private List<View> popupViews = new ArrayList<>();

    private TimeDropDownAdapter timeAdapter;
    private LookatAdapter adapter;
    private NewLookatAdapter newAdapter;

    public String startTime = "";
    public String endTime = "";
    private JSONObject jsonObject = new JSONObject();
    private int page = 1;
    private boolean mLoadingLock = false;

    private String csCode;
    private String type;
    private GirdDropDownAdapter stateAdapter;
    private boolean isSecondHand = true;

    public static LookAtFragment newInstance(String code, String type) {
        LookAtFragment fragment = new LookAtFragment();
        Bundle args = new Bundle();
        args.putString("code", code);
        args.putString("type", type);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            csCode = getArguments().getString("code");
            type = getArguments().getString("type");
        }
    }
    private FragmentLookAtBinding binding;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_look_at, null);
            binding = DataBindingUtil.bind(view);
            initView();
            getData();

        }
        // 缓存的rootView需要判断是否已经被加过parent，
        // 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null) {
            parent.removeView(view);
        }
        binding = DataBindingUtil.bind(view);
        return view;
    }

    /**
     * 初始化视图
     */
    private void initView() {

        ArrayList<Map<String, Object>> dataList = new ArrayList<>();
        adapter = new LookatAdapter(dataList);
        newAdapter = new NewLookatAdapter(dataList);

        binding.refreshLayout.setColorSchemeResources(R.color.yellow, R.color.light_yellow);
        binding.refreshLayout.setOnRefreshListener(this);

        ListView stateView = new ListView(getActivity());
        stateAdapter = new GirdDropDownAdapter(getActivity(), Arrays.asList(typeArr));
        stateView.setAdapter(stateAdapter);

        stateView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                stateAdapter.setCheckItem(i);
                binding.dropDownMenu.setTabText(i == 0 ? headers[0] : typeArr[i]);
                switch (i) {
                    case 0:
                        page = 1;
                        isSecondHand = true;
                        binding.lookRecyclerView.setAdapter(adapter);
                        getData();
                        break;
                    case 1:
                        page = 1;
                        isSecondHand = false;
                        binding.lookRecyclerView.setAdapter(newAdapter);
                        getNewData();
                        break;
                }

                binding.dropDownMenu.closeMenu();
            }
        });

        //init time menu
        final ListView timeView = new ListView(getActivity());
        final View priceAreaFooter = getActivity().getLayoutInflater().inflate(R.layout.time_menu_footer, null);
        timeAdapter = new TimeDropDownAdapter(getActivity(), Arrays.asList(time));
        timeView.addFooterView(priceAreaFooter);
        timeView.setAdapter(timeAdapter);
        timeView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                show(time[i]);
                timeAdapter.setCheckItem(i);
            }
        });

        //重置、确定按钮
        TextView cancel = priceAreaFooter.findViewById(R.id.bt_cancel);
        TextView confirm1 = priceAreaFooter.findViewById(R.id.bt_confirm);

        //点击重置
        cancel.setOnClickListener(v -> {
            timeAdapter.startTime = "";
            timeAdapter.endTime = "";
            startTime = "";
            endTime = "";
            binding.dropDownMenu.setTabText("带看时间");
            timeAdapter.notifyDataSetChanged();
        });

        //确定按钮
        confirm1.setOnClickListener(v -> {

            if (isSecondHand) {
                getData();
            } else {
                getNewData();
            }
            binding.dropDownMenu.closeMenu();
        });

        //init popupViews
        popupViews.add(stateView);
        popupViews.add(timeView);

        TextView contentView = new TextView(getActivity());
        contentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0));
        contentView.setGravity(Gravity.CENTER);

        //init dropdownview
        binding.dropDownMenu.setDropDownMenu(Arrays.asList(headers), popupViews, contentView);

        binding.lookRecyclerView.setHasFixedSize(true);
        binding.lookRecyclerView.setLayoutManager(new WrapContentLinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        binding.lookRecyclerView.enableAutoLoadMore(this);


        adapter.changeMode(YfListMode.MODE_LOADING);
        binding.lookRecyclerView.setAdapter(adapter);
    }

    @Override
    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
        if (timePickerView.getTitle().equals("最早日期")) {
            startTime = DateUtil.getTimeStart(millseconds);
            timeAdapter.startTime = startTime;
        } else if (timePickerView.getTitle().equals("最晚日期")) {
            endTime = DateUtil.getTimeEnd(millseconds);
            timeAdapter.endTime = endTime;
        }
        timeAdapter.notifyDataSetChanged();
        if (!TextUtils.isEmpty(startTime) && !TextUtils.isEmpty(endTime)) {
            binding.dropDownMenu.setTabText(startTime + "—" + endTime);
        } else {
            binding.dropDownMenu.setTabText(startTime + endTime);
        }
    }

    public void show(String title) {
        TimePickerDialog timePicker = new TimePickerDialog.Builder()
                .setType(Type.YEAR_MONTH_DAY)
                .setTitleStringId(title)
                .setCurrentMillseconds(System.currentTimeMillis())
                .setThemeColor(getResources().getColor(R.color.yellow))
                .setWheelItemTextNormalColor(getResources().getColor(R.color.hintColor))
                .setWheelItemTextSelectorColor(getResources().getColor(R.color.yellow))
                .setCallBack(this)
                .build();
        timePicker.show(getActivity().getSupportFragmentManager(), "year_month_day");
    }

    private void getData() {
        jsonObject.clear();
        jsonObject.put("csCode", csCode);
        if (type.equals("rent")) {
            jsonObject.put("type", 0);
        } else {
            jsonObject.put("type", 1);
        }
        jsonObject.put("pageSize", 20);
        jsonObject.put("pageIndex", page);

        if (!TextUtils.isEmpty(startTime) || !TextUtils.isEmpty(endTime)) {
            jsonObject.put("showStartTime", startTime);
            jsonObject.put("showEndTime", endTime);
        } else {
            jsonObject.remove("showStartTime");
            jsonObject.remove("showEndTime");
        }
        OkHttpUtils.postString()
                .url(ApiConfig.VISIT_LIST)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(getActivity(), response, adapter)) {
                            JSONArray data = JSON.parseArray(response.get("data").toString());
//                            //数据列表
                            ArrayList<Map<String, Object>> list = JSON.parseObject(data.toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            if (page == 1) {
                                adapter.setData(list);
                            } else {
                                adapter.addData(list);
                            }
                        } else if (response.get("code").toString().equals("303")) {
                            //没有更多
                            page--;
                        }
                        if (binding.refreshLayout.isRefreshing())
                            binding.refreshLayout.setRefreshing(false);
                        mLoadingLock = false;
                    }
                });

    }

    private void getNewData() {
        jsonObject.clear();
        jsonObject.put("customerCode", csCode);
        jsonObject.put("pageSize", "20");
        jsonObject.put("pageIndex", StringUtil.valueOf(page));
        if (!TextUtils.isEmpty(startTime) || !TextUtils.isEmpty(endTime)) {
            jsonObject.put("showStartTime", startTime);
            jsonObject.put("showEndTime", endTime);
        } else {
            jsonObject.remove("showStartTime");
            jsonObject.remove("showEndTime");
        }
        OkHttpUtils.postString()
                .url(ApiConfig.CUSTOMER_NEW_VISIT_LIST)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(getActivity(), response, newAdapter)) {
                            JSONArray data = JSON.parseArray(response.get("data").toString());
//                            //数据列表
                            ArrayList<Map<String, Object>> list = JSON.parseObject(data.toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            if (page == 1) {
                                newAdapter.setData(list);
                            } else {
                                newAdapter.addData(list);
                            }
                        } else if (response.get("code").toString().equals("303")) {
                            //没有更多
                            page--;
                        }
                        if (binding.refreshLayout.isRefreshing())
                            binding.refreshLayout.setRefreshing(false);
                        mLoadingLock = false;
                    }
                });
    }

    @Override
    public void loadMore() {
        if (mLoadingLock) {
            return;
        }
        mLoadingLock = true;
        page++;
        if (isSecondHand) {
            getData();
        } else {
            getNewData();
        }
    }

    @Override
    public void onRefresh() {
        page = 1;
        if (isSecondHand) {
            getData();
        } else {
            getNewData();
        }
    }
}
